let App = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    not_login:0,
    dataType: 'userInit',
    list: [],
    scrollHeight: null,
    no_more: false, // 没有更多数据
    isLoading: true, // 是否正在加载中
    page: 1, // 当前页码
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // console.log(options.type);
    let _this = this;
    _this.setListHeight();
    this.data.dataType = options.type || 'userInit';
    this.setData({
      dataType: this.data.dataType
    });
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // let team = this.data.list;
    let dataType = this.data.dataType;
    
    // 获取订单列表
    // if (dataType == 'userSelect' ) {
    //   this.getOrderList();
    // }
    // 获取订单列表
    this.getOrderList();
    // 统计个状态活动的数量
    this.getUserActiveNUm();
    //倒计时
    this.countDown();  
  },

  onHide: function () {
    //页面隐藏
    // console.log('onHide');
    clearInterval(this.data.timer);
  },
  onUnload: function () {
    //页面关闭
    // console.log('onUnload');
    clearInterval(this.data.timer);
  },

  // 统计个状态活动的数量
  getUserActiveNUm: function () {
    let _this = this;
    App._get('user.index/getUserActiveNUm', {}, function (result) {
      _this.setData(result.data);
    });
  },

  /**
   * 获取订单列表
   */
  getOrderList: function(isPage, page) {
    let _this = this;
    // console.log(_this.data.dataType);
    //App._get('user.order/lists', {
    App._get('doing/getList', {
      page: page || 1,
      dataType: _this.data.dataType,
      rand: 1,
      shoppingMallId:0,
      shop_cate: 0,
      coupon_type: 0,//类别
      people_num: 0,//参与人数
      time: 0,//参与时间
    }, function(result) {
      //console.log(result);
      if (result.data.code == 2){
        _this.setData({
          not_login: 1
        });
        return false;
      }


      let resList = result.data.list;
      if(resList != ''){
        for (let i = 0; i < resList.data.length; i++) {
          resList.data[i]['root'] = App.root;
        }
      }
      if (isPage == true) {
        _this.setData({
          'list.data': _this.data.list.data.concat(resList.data),
          user_id: result.data.user_id,
          isLoading: false,
        });
      } else {
        _this.setData({
          list: resList,
          user_id: result.data.user_id,
          isLoading: false,
        });
      }
    });
    
  },
  /**
   * 切换标签
   */
  bindHeaderTap: function(e) {
    this.setData({
      dataType: e.currentTarget.dataset.type,
      list: {},
      isLoading: true,
      page: 1,
      no_more: false,
    });
    // 获取订单列表
    this.getOrderList(e.currentTarget.dataset.type);
    this.getUserActiveNUm();
  },

  /**
   * 取消订单
   */
  cancelOrder: function(e) {
    let _this = this;
    let order_id = e.currentTarget.dataset.id;
    wx.showModal({
      title: "友情提示",
      content: "确认要取消该订单吗？",
      success: function(o) {
        if (o.confirm) {
          App._post_form('user.order/cancel', {
            order_id
          }, function(result) {
            _this.getOrderList(_this.data.dataType);
          });
        }
      }
    });
  },

  /**
   * 确认收货
   */
  receipt: function(e) {
    let _this = this;
    let order_id = e.currentTarget.dataset.id;
    wx.showModal({
      title: "提示",
      content: "确认收到商品？",
      success: function(o) {
        if (o.confirm) {
          App._post_form('user.order/receipt', {
            order_id
          }, function(result) {
            _this.getOrderList(_this.data.dataType);
          });
        }
      }
    });
  },

  /**
   * 发起付款
   */
  // payOrder: function(e) {
  //   let _this = this;
  //   let order_id = e.currentTarget.dataset.id;

  //   // 显示loading
  //   wx.showLoading({
  //     title: '正在处理...',
  //   });
  //   App._post_form('user.order/pay', {
  //     order_id
  //   }, function(result) {
  //     console.log(result);
  //     if (result.code === -10) {
  //       App.showError(result.msg);
  //       return false;
  //     }
  //     // 发起微信支付
  //     wx.requestPayment({
  //       timeStamp: result.data.timeStamp,
  //       nonceStr: result.data.nonceStr,
  //       package: 'prepay_id=' + result.data.prepay_id,
  //       signType: 'MD5',
  //       paySign: result.data.paySign,
  //       success: function(res) {
  //         // 跳转到已付款订单
  //         wx.navigateTo({
  //           url: '../order/detail?order_id=' + order_id
  //         });
  //       },
  //       fail: function() {
  //         App.showError('订单未支付');
  //       },
  //     });
  //   }, null, function() {
  //     wx.hideLoading();
  //   });
  // },

  /**
   * 订单评价
   */
  comment: function(e) {
    let _this = this;
    let order_id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: './comment/comment?order_id=' + order_id,
    })
    //console.log(order_id);
  },

  /**
   * 跳转订单详情页
   */
  navigateToDetail: function(e) {
    let order_id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../order/detail?order_id=' + order_id
    });
  },

  onPullDownRefresh: function() {
    wx.stopPullDownRefresh();
  },

  /**
   * 下拉到底加载数据
   */
  bindDownLoad: function() {
    // 已经是最后一页
    if (this.data.page >= this.data.list.last_page) {
      this.setData({
        no_more: true
      });
      return false;
    }
    // 加载下一页列表
    this.getOrderList(true, ++this.data.page);
  },

  /**
   * 设置商品列表高度
   */
  setListHeight: function () {
    let systemInfo = wx.getSystemInfoSync(),
      rpx = systemInfo.windowWidth / 750, // 计算rpx
      tapHeight = Math.floor(rpx * 88), // tap高度
      scrollHeight = systemInfo.windowHeight - tapHeight; // swiper高度
    this.setData({
      scrollHeight
    });
  },

  //跳转 用户详情页
  goToDetail: function (e) {
    let user_id = e.currentTarget.dataset.user_id;
    wx.navigateTo({
      url: '/pages/social/detail?user_id=' + user_id
    })
  },

  //放弃使用优惠券
  unUseCoupon: function (e) {
    let _this = this;
    let doing_id = e.currentTarget.dataset.doing_id;
    let coupon_id = e.currentTarget.dataset.coupon_id;

    wx.showModal({
      title: '提示',
      content: '您确定要取消发起吗？',
      success(res) {
        if (res.confirm) {
          App._get('Doing/unUseCoupon', {
            coupon_id: coupon_id,
            doing_id: doing_id
          }, function (result) {
            if (result.code == 1) {
              wx.navigateBack();
            }
          });
        } else if (res.cancel) {
          //console.log('用户点击取消')
        }
      }
    })
  },


  /**
  * 确认邀约
  */
  isConfirm:function(e){
    let doing_id = e.currentTarget.dataset.doing_id;
    let pair_time = e.currentTarget.dataset.pair_time;
    wx.showModal({
      title: '提示',
      content: '赴约时间为'+pair_time+'分，决定赴约请按确定',
      success(res) {
        if (res.confirm) {
          App._get('Doing/isConfirm', {
            pair_time: pair_time,
            doing_id: doing_id
          }, function (result) {
            //console.log(result);
            if (result.code == 1) {
              //wx.navigateBack();
              // 跳转到订单详情
              wx.redirectTo({
                url: '/pages/doing/user/index?type=userGather',
              });
            }
          });
        } else if (res.cancel) {
          //console.log('用户点击取消')
        }
      }
    })

  },


  /**
   * 发起付款
   */
  payOrder: function (e) {
    let _this = this;
    let doing_user_id = e.currentTarget.dataset.doing_user_id;
    // 显示loading
    wx.showLoading({
      title: '正在处理...',
    });
    App._post_form('doing/pay', {
      doing_user_id
    }, function (result) {
      //console.log(result);
      if (result.code === -10) {
        App.showError(result.msg);
        return false;
      }
      // 发起微信支付
      wx.requestPayment({
        timeStamp: result.data.timeStamp,
        nonceStr: result.data.nonceStr,
        package: 'prepay_id=' + result.data.prepay_id,
        signType: 'MD5',
        paySign: result.data.paySign,
        success: function (res) {
          //console.log(res);
          _this.getOrderList();
          _this.getUserActiveNUm();
          //console.log(res);
          // 跳转到已付款订单
          // wx.navigateTo({
          //   url: '../order/detail?order_id=' + order_id
          // });
        },
        fail: function () {
          //App.showError('订单未支付');
        },
      });

    }, null, function () {
      wx.hideLoading();
    });
    
  },



  dump_assign_coupon: function (e) {
    let doing_id = e.currentTarget.dataset.doing_id;
    let coupon_id = e.currentTarget.dataset.coupon_id;
    let user_coupon_id = e.currentTarget.dataset.user_coupon_id;
    let status = this.data.dataType;
    wx.navigateTo({
      url: '/pages/coupon/detail?status=' + status + '&coupon_id=' + coupon_id + '&user_coupon_id=' + user_coupon_id +'&doing_id='+doing_id
    })
  },

  dump_makeup: function (e) {
    let doing_id = e.currentTarget.dataset.doing_id;
    let coupon_id = e.currentTarget.dataset.coupon_id;
    let user_coupon_id = e.currentTarget.dataset.user_coupon_id;
    let status = this.data.dataType;
    wx.navigateTo({
      url: '/pages/coupon/detail?status=' + status + '&coupon_id=' + coupon_id + '&user_coupon_id=' + user_coupon_id + '&doing_id=' + doing_id
    })
  },

  dump_ren_detail: function (e) {
    let coupon_id = e.currentTarget.dataset.coupon_id;
    let address_id = e.currentTarget.dataset.address_id;
    let status_type = e.currentTarget.dataset.status_type;
    let pair_id = e.currentTarget.dataset.pair_id;
    let pair_type = e.currentTarget.dataset.pair_type;

    let status = this.data.dataType;
    if (status_type == 'renzheng' ){
      wx.navigateTo({
        url: '/pages/coupon/ren_detail?coupon_id=' + coupon_id + '&address_id=' + address_id + '&status_type=' + status
      })
    }
    if (status_type == 'pair') {
      wx.navigateTo({
        url: '/pages/social/pair_detail?pair_id=' + pair_id + '&pair_type=' + pair_type + '&status=' + status
      })
    }
  },
  // dump_ren_coupon: function (e) {
  //   let coupon_id = e.currentTarget.dataset.coupon_id;
  //   //let address_id = this.data.address_id;
  //   wx.navigateTo({
  //     url: '/pages/coupon/ren_detail?coupon_id=' + coupon_id
  //   })
  // },


  timeFormat(param) {//小于10的格式化函数
    return param < 10 ? '0' + param : param;
  },
  countDown() {//倒计时函数
    let _this = this;
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();
    //let endTimeList = this.data.actEndTimeList;
    let endTimeList = _this.data.list;
    let countDownArr = [];
    if (endTimeList.data){
      for (let i = 0; i < endTimeList.data.length; i++) {
        let endTime = new Date(endTimeList.data[i].timett).getTime();
        let obj = null;
        // 如果活动未结束，对时间进行处理
        if (endTime - newTime > 0) {
          let time = (endTime - newTime) / 1000;
          // 获取天、时、分、秒
          let day = parseInt(time / (60 * 60 * 24));
          let hou = parseInt(time % (60 * 60 * 24) / 3600);
          let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
          let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
          obj = {
            day: this.timeFormat(day),
            hou: this.timeFormat(hou),
            min: this.timeFormat(min),
            sec: this.timeFormat(sec)
          }
        } else {//活动已结束，全部设置为'00'
          obj = {
            day: '00',
            hou: '00',
            min: '00',
            sec: '00'
          }
        }
        endTimeList.data[i]['time'] = obj;
      }
      // 渲染，然后每隔一秒执行一次倒计时函数
      this.setData({ 'list.data': endTimeList.data })
    }
    //setTimeout(this.countDown, 1000);
    this.setData({ timer: setTimeout(this.countDown, 1000) })
  },

  //取消报名加入
  uncancel: function (e) {
    let _this = this;
    //let doing_user_id = e.currentTarget.dataset.doing_user_id;
    let doing_id = e.currentTarget.dataset.doing_id;
    let coupon_id = e.currentTarget.dataset.coupon_id;
    wx.showModal({
      title: '提示',
      content: '您确定要取消报名吗？',
      success(res) {
        if (res.confirm) {
          App._get('doing/uncancel', {
            doing_user_id: '',
            doing_id: doing_id,
            coupon_id: coupon_id
          }, function (result) {
            //console.log(result);
            if (result.code == 1) {
              wx.navigateBack()
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  //发起集合
  goToUserGather: function (e) {
    let _this = this;
    let doing_id = e.currentTarget.dataset.doing_id;
   //console.log(doing_id);
    wx.showModal({
      title: '提示',
      content: '发起集合不可逆转，未被选中的用户将会被退回押金，您确定要发起集合吗？',
      success(res) {
        if (res.confirm) {
          App._get('doing/goToUserGather', {
            doing_id: doing_id
          }, function (result) {
            //console.log(result);
            wx.redirectTo({
              url: '/pages/doing/user/index?type=userGather'
            })
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  useDoing:function(e){
    let doing_id = e.currentTarget.dataset.doing_id;
    let doing_user_id = e.currentTarget.dataset.doing_user_id;
    //console.log(doing_user_id);
    wx.navigateTo({
      url: '/pages/qrcode/index?type=normal&doing_user_id=' + doing_user_id + '&doing_id=' + doing_id
    })
  },

  //登录
  login: function () {
    // 跳转授权页面
    wx.navigateTo({
      url: "/pages/login/login"
    });
  },

});